/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.system.domain.DictType;
import com.koron.system.service.api.DictTypeService;
import com.koron.system.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

@Api(tags = "dictType", description = "字典类型接口类")
@RestController
@RequestMapping("/dictType")
public class DictTypeController {
    @Autowired
    private DictTypeService dictTypeService;


    @ApiOperation("保存字典类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id主键,新增时不传，修改时必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "字典类型名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictKey", value = "字典类型key", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictIndex", value = "字典类型排序值", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String id, @RequestParam(required = true) final String name,
                                     @RequestParam(required = true) final String dictKey, @RequestParam(required = true) final Integer dictIndex,
                                     @RequestParam(required = false) final String remark) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(name)) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_NAME.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_NAME.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(dictKey)) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_KEY.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_KEY.getDescription());
            return msg;
        }
        if (null == dictIndex) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_INDEX.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_INDEX.getDescription());
            return msg;
        }
        DictType type = new DictType();
        Date time = new Date();
        type.setUpdateTime(time);
        type.setUpdateUser(user == null ? null : user.getName());
        type.setId(id);
        type.setDictIndex(dictIndex);
        type.setName(name);
        type.setDictKey(dictKey);
        type.setRemark(remark);
        msg = dictTypeService.saveDictType(type);
        return msg;
    }


    @ApiOperation("批量修改字典类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictTypes", value = "字典类型修改数据，json字符串,格式为[{\"id\": \"\",\"name\": \"\",\"dictKey\": \"\",\"dictIndex\": \"\",\"remark\": \"\",}]", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchUpdate.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchUpdate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                            @RequestParam final String dictTypes) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(dictTypes)) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_UPDATE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_UPDATE_DATA.getDescription());
            return msg;
        }
        List<DictType> dictTypeList = new ArrayList<>();
        JSONArray array = JSON.parseArray(dictTypes);
        StringBuilder descriptions = new StringBuilder();
        if (array != null && !array.isEmpty()) {
            Iterator<Object> it = array.iterator();
            while (it.hasNext()) {
                JSONObject json = (JSONObject) it.next();
                String id = json.getString("id");
                String name = json.getString("name");
                String dictKey = json.getString("dictKey");
                Integer dictIndex = json.getInteger("dictIndex");
                String remark = json.getString("remark");
                if (StringUtils.isEmpty("id")) {
                    descriptions.append(name).append("-").append(dictKey).append(",");
                } else {
                    DictType type = new DictType();
                    Date time = new Date();
                    type.setUpdateTime(time);
                    type.setUpdateUser(user == null ? null : user.getName());
                    type.setId(id);
                    type.setDictIndex(dictIndex);
                    type.setName(name);
                    type.setDictKey(dictKey);
                    type.setRemark(remark);
                    dictTypeList.add(type);
                }
            }
        }
        if (null != dictTypeList && dictTypeList.size() > 0) {
            msg = dictTypeService.batchUpateDictType(dictTypeList);
            if (StringUtils.isNotEmpty(descriptions.toString())) {
                msg.setDescription("批量修改成功，但由于这些字典类型名称-字典类型key:" + descriptions.toString() + "的id没有传值，对这些数据没有进行处理");
            }
            return msg;
        }
        msg.setCode(-1);
        msg.setDescription("暂无数据修改");
        return msg;
    }


    @ApiOperation("批量删除字典类型")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "字典类型id,多个之间用，分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    public MessageBean<Integer> batchDelete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(ids)) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        String[] idArray = ids.split("[,，]");
        if (idArray.length > 0) {
            msg = dictTypeService.batchDeteleDictType(Arrays.asList(idArray));
            return msg;
        }
        msg.setCode(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getCode());
        msg.setDescription(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getDescription());
        return msg;
    }


    @ApiOperation("根据主键id获取字典类型详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "字典类型id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<DictType> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String id) {
        if (null == user) {
            MessageBean<DictType> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DictType> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getCode());
            msg.setDescription(BusinessCode.DICTTYPE_EMPTY_CHANGE_DATA.getDescription());
            return msg;
        }
        msg = dictTypeService.queryOneDictType(id);
        return msg;
    }


    @ApiOperation("获取字典类型列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<DictType>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<DictType>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<DataBean<DictType>> msg = new MessageBean<>();
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = dictTypeService.queryAllDictType(start, pageSize);
        msg.getData().setPageNo(page);
        msg.getData().setPageSize((pageSize == null || pageSize == 0) ? 10 : pageSize);
        return msg;
    }


    @ApiOperation("根据名称模糊查询字典类型和字典数据列表信息")
    @RequestMapping(value = "/queryByGroupType.htm", method = RequestMethod.POST)
    public MessageBean<List<DictType>> getDictTypesAndDictDatas(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam(required = false)String name) {
        if (null == user) {
            MessageBean<List<DictType>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<List<DictType>> msg = dictTypeService.getDictTypesAndDictDatas(name);
        return msg;
    }

}
